package ReflectDemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/*
    通过反射实现如下操作：
        Student s = new Student("Jack");
        System.out.println(s);
 */
public class ReflectDemo3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> aClass = Class.forName("ReflectDemo.Stu");
        Constructor<?> constructor = aClass.getDeclaredConstructor(String.class);
        //Object obj = constructor.newInstance("Jack");   //不能通过私有构造方法创建对象，会报异常
                                                          //报异常 : class ReflectDemo.ReflectDemo3 cannot access a member of class ReflectDemo.Stu with modifiers "private"

        //暴力反射
        constructor.setAccessible(true); //设置值为true,取消访问检查
        Object obj = constructor.newInstance("Jack");

        System.out.println(obj);
    }
}
